package com.zmn.plat.admin.controller.part.relation;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.zmn.common.dto2.ResponseDTO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dto.ResultDTO;
import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.plat.admin.controller.part.PartBaseController;
import com.zmn.plat.model.entity.part.PartSkuRelation;
import com.zmn.plat.model.entity.part.PartSkuRelationDTO;

/**
 * 类描述： PartSkuRelationListController
 *
 * @author XiangJunMing
 * @since 2019/03/23 20:36
 */
@RestController
@RequestMapping("/part/relation")
public class PartSkuRelationModifyController extends PartBaseController {

    private Logger logger = LoggerFactory.getLogger(PartSkuRelationModifyController.class);

    /**
     * 描述: 跳转到配件关联页（添加修改）
     *
     * @author XiangJunMing
     * @since 2019/03/23 20:34
     */
    @RequestMapping(value = {"ajax/addEdit"})
    @RequiresPermissions("/part/relation/addEdit.action")
    public ResponseDTO doAddEdit(@RequestBody PartSkuRelation entity) {

        List<PartSkuRelationDTO> partSkuRelationDTOS = partSkuRelationService.listByOneSkuId(entity.getOneSkuId());
        List<Integer> manySkuIds = partSkuRelationDTOS.stream().map(PartSkuRelation::getManySkuId).collect(Collectors.toList());
        if (manySkuIds.contains(entity.getManySkuId())) {
            return ResponseDTO.fail("配件关联已存在！");
        }

        LoginStaff mcStaff = getMcStaff();
        entity.setCreater(mcStaff.getRealName());
        entity.setUpdater(mcStaff.getRealName());
        entity.setUpdateTime(new Date());

        partSkuRelationService.insert(entity);

        return ResponseDTO.success(true,"配件关联成功！");
    }

    /**
     * 描述: 跳转到配件关联页（添加修改）
     *
     * @author XiangJunMing
     * @since 2019/03/23 20:34
     */
    @RequestMapping(value = {"ajax/del"})
    @RequiresPermissions("/part/relation/del.action")
    public ResponseDTO del(Integer relationId) {

        if (relationId == null || relationId == 0) {
            return ResponseDTO.fail("relationId不能为空！");
        }

        PartSkuRelation byKey = partSkuRelationService.findByKey(relationId);
        if (byKey == null || byKey.getRelationId() == null || !byKey.getRelationId().equals(relationId)) {
            return ResponseDTO.fail("删除失败！数据不存在！");
        }

        partSkuRelationService.deleteByKey(relationId);

        return ResponseDTO.success(true,"删除配件关联成功！");
    }

}
